<?php
/**
 *  国家和地区管理
*/

namespace app\admin\service;

use app\api\model\RegionCity;
use app\api\model\RegionCountry;

use app\facade\Basic;



class Region extends BaseService
{

    /**
     *  获取国家列表
    */
    public function getCountryList($param)
    {
        $where = '';
        $result = RegionCountry::field("id,concat (cname,' (',name,') ') as name,country_code,full_name,code");
        #分类国家接口查询没有分类的国家列表
        if($param && $param['is_classification'] == true){
            $where = 'ccname_id is null';
            if(isset($param['id']) && $param['id']){
                $where = 'ccname_id is null or ccname_id ='.$param['id'];
            }
            $result = $result ->whereRaw($where);
        }
        $result = $result->select();
        return Basic::data(0,'common.success',$result);
    }

    /**
     *  获取城市
    */
    public function getCityList($param)
    {
        $result = RegionCity::where('country_id',$param['country_id'])->field('id,state,name,lower_name')->select();
        return Basic::data(0,'common.success',$result);
    }

    /**
     *  获取省和城市
    */
    public function area($param)
    {

        $result = RegionCity::where('country_id',$param['country_id'])->select();



        if( !$result ) {
            return Basic::data(0,'common.success',[]);
        }

        $result = $result->toArray();


        $result_all = [];
        foreach ($result as $value) {
            $result_all[$value['state']][] = $value;
        }




        $state = [];
        $city = [];
        $i = 0;
        $ii = 0;
        foreach ($result_all as $key=>$item) {

            foreach ($item as $value){

                if ($key!=''){
                    $state[$i]['id'] = $value['state_code'];
                    $state[$i]['name'] = $value['state'];
                }

                $city[$ii]['id'] = $value['id'];
                $city[$ii]['name'] = $value['name'];
                $city[$ii]['state_id'] = !empty($value['state_code']) ? $value['state_code'] : '';

                $ii++;
            }
            $i ++;
        }




        return Basic::data(0,'common.success',[
            'state' => $state,
            'city' => $city,
        ]);

    }

}
